/*
 * @Description: input 标签输入
 * @Autor: gufuyan
 * @Date: 2021-12-03 16:07:19
 * @lastModifiedBy: gufuyan
 * @LastEditTime: 2021-12-03 16:08:44
 * @lastModifiedContent:
 */
import React, { useState, useRef } from 'react';
import { Input, Space, Tag } from 'antd';
import { CloseCircleOutlined } from '@ant-design/icons';
import type { Option } from './data';

/**
 * input 标签输入
 * @param
 * @returns  JSX
 */
const InputTagList: React.FC<{
  value?: Option[];
  onChange?: (value: Option[]) => void;
}> = ({ value, onChange }) => {
  const ref = useRef<Input | null>(null);

  const [newTags, setNewTags] = useState<Option[]>([]);
  const [inputValue, setInputValue] = useState<string>('');

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    let tempsTags = [...(value || [])];
    if (inputValue && tempsTags.filter((tag) => tag.label === inputValue).length === 0) {
      tempsTags = [...tempsTags, { value: inputValue, label: inputValue }];
    }
    onChange?.(tempsTags);
    setNewTags([]);
    setInputValue('');
  };

  let currentValue: Option[] | undefined = value;
  if (value && typeof value === 'string') {
    currentValue = [
      {
        value: value,
        label: value,
      },
    ];
  }

  return (
    <Space>
      {(currentValue || []).concat(newTags).map((item: Option, index: number) => (
        <Tag key={item.value}>
          {item.label}
          <CloseCircleOutlined
            onClick={() => {
              const tempsTags: Option[] = [...(currentValue || [])];
              tempsTags.splice(index, 1);

              onChange?.(tempsTags);
              setNewTags([]);
              setInputValue('');
            }}
            style={{ color: 'red', marginLeft: '10px', cursor: 'pointer' }}
          />
        </Tag>
      ))}
      <Input
        ref={ref}
        type="text"
        size="small"
        placeholder="请输入"
        style={{ width: 78 }}
        value={inputValue}
        onChange={handleInputChange}
        onBlur={handleInputConfirm}
        onPressEnter={handleInputConfirm}
      />
    </Space>
  );
};

export default InputTagList;
